package com.vma.jifu.backsys.controller;


import com.alipay.api.AlipayClient;
import com.alipay.api.DefaultAlipayClient;
import com.alipay.api.request.AlipayTradeRefundRequest;
import com.alipay.api.response.AlipayTradeRefundResponse;
import com.jfinal.core.Controller;
import com.jfinal.plugin.activerecord.Page;
import com.jfinal.plugin.activerecord.Record;
import com.vma.jifu.bizModel.model.*;
import com.vma.jifu.offer.service.OfferService;
import com.vma.jifu.offer.service.impl.OfferServiceImpl;
import com.vma.jifu.orderList.service.OrderService;
import com.vma.jifu.orderList.service.impl.OrderServiceImpl;
import com.vma.tools.ReturnsUtil;
import com.vma.tools.alipay.AlipayConfig;

import java.text.DecimalFormat;
import java.util.Date;
import java.util.List;

/**
 * Created by kitabi on 2017/6/16.
 */
public class OrderController extends BaseController {

    OrderService orderService= new OrderServiceImpl();

    OfferService offerService = new OfferServiceImpl();

    public void qryOrderList(){
        try {
            Integer cPage = getParaToInt("cPage");
            Integer pSize = getParaToInt("pSize");

            String ordernbr =getPara("ordernbr");
            String mystatus = getPara("status");
            String start = getPara("start");
            String end = getPara("end");
            String offerName = getPara("offerName");

            String province = getPara("province");
            String city = getPara("city");
            String area = getPara("area");
            Page<Record> offer= orderService.qryOrderList(cPage,pSize,mystatus,ordernbr,province,city,area,start,end,offerName);


            renderJson(ReturnForm(offer.getList(),offer.getTotalRow()));
        }catch (Exception e){
            e.printStackTrace();
            renderJson(ReturnsUtil.returnException(e.getMessage(),e));
        }
    }

    public void updateStatus(){
        Integer mystatus = getParaToInt("status");
        String idlist = getPara("id");
        String[] ids= idlist.split(",");
        for( String id : ids){
            OrderList comment = OrderList.dao.findById(id);




            //如果是退款动作还得增加消息
            if(mystatus == 7){
//假如是阿里渠道付款
                int payway= comment.getPayType();
                if(payway==1){
                    DecimalFormat decimalFormat=new DecimalFormat(".00");
                    String fee=decimalFormat.format(comment.getTotalFee()/100);
                    //阿里退款
                    comment.setStatus(6).update();

                    String order_nbr= comment.getOrderNbr();
                    boolean alipayreturn =refund(order_nbr,"",fee,comment);
                    if(alipayreturn) {//退款成功
                        renderJson(ReturnsUtil.returnSuccess("修改成功"));
                    }else {
                        comment.setStatus(mystatus).update();
                        renderJson(ReturnsUtil.returnSuccess("修改失败"));
                    }
                }else if(payway==2){//微信


                    comment.setStatus(mystatus).update();
                    renderJson(ReturnsUtil.returnSuccess("修改成功"));
                }


            }else if(mystatus == 6){




            }else{
                comment.setStatus(mystatus).update();
                renderJson(ReturnsUtil.returnSuccess("修改成功"));
            }

        }


    }

    public  boolean refund(String outTradeNo,String tradeNo,String refundAmount,OrderList commont)  {
        AlipayClient alipayClient = new DefaultAlipayClient(
                "https://openapi.alipay.com/gateway.do",AlipayConfig.app_id,
                AlipayConfig.private_key,
                "json",
                "utf-8",
                AlipayConfig.ali_public_key,
                "RSA2");
        AlipayTradeRefundRequest request = new AlipayTradeRefundRequest();
        request.setBizContent("{" +
                "\"out_trade_no\":"+outTradeNo+"," +
//                "\"trade_no\":"+tradeNo+"," +
                "\"refund_amount\":0.01}");
        AlipayTradeRefundResponse response = null;
        try {
            response = alipayClient.execute(request);
        } catch (Exception e) {
            e.printStackTrace();
        }
        String ifsuccess= response.getMsg();

        if( response.getMsg()=="Success"){

            SystemMessage systemMessage = new SystemMessage();
            OrderList orderList = OrderList.dao.findById(commont.getId());
            User user = User.dao.findById(orderList.getUserId());
            String message = "您申请的订单退款已完成，请注意查收！\n订单编号：" + orderList.getOrderNbr();
            systemMessage.setContent(message).setTitle("会员订单：退款成功通知：").setCreateTime(new Date()).setType(2).setIsDelete(0).setStatus(1).save();

            Message2User message2User = new Message2User();
            message2User.setUserId(orderList.getUserId()).setMessageId(systemMessage.getId()).setCreateTime(new Date()).setIsDelete("0");
            message2User.update();

            //更新tgAward表
            TgAward tgAward = TgAward.dao.findFirst("select * from tg_award where order_id = "+commont.getId());

            tgAward.setStatus(-1).update();

            commont.setStatus(7).update();
            return true;
        } else {
            return false;
        }
    }

    public void qryCommentList(){

            Integer cPage = getParaToInt("cPage");
            Integer pSize = getParaToInt("pSize");
            String name =getPara("content");
            String mystatus = getPara("status");
            String start = getPara("start");
            String end = getPara("end");
            Page<OfferComment> offer= offerService.qyrCommentList(cPage,pSize,name,mystatus,start,end);
            renderJson(ReturnForm(offer.getList(),offer.getTotalRow()));

    }

    public void updateCommentStatus(){
        Integer mystatus = getParaToInt("status");
        String idlist = getPara("id");
        String[] ids= idlist.split(",");
        for( String id : ids){
            OfferComment comment = OfferComment.dao.findById(id);
            comment.setStatus(mystatus).update();

        }
        renderJson(ReturnsUtil.returnSuccess("修改成功"));


    }

    public void deleteCommont(){

        String idlist = getPara("id");
        String[] ids= idlist.split(",");
        for( String id : ids) {

            OfferComment comment = OfferComment.dao.findById(id);

            comment.delete();
        }

        renderJson(ReturnsUtil.returnSuccess("删除成功"));
    }

    public void queryExpress(){
        List<Express> expressList= Express.dao.find("select * from express");

        renderJson(expressList);
    }

    public void saveExpress(){
        String id = getPara("id");
        int expressid= getParaToInt("express_id");
        String express_num= getPara("express_num");

        OrderList order= OrderList.dao.findById(id);
        order.setStatus(3).setExpressId(expressid).setExpressNumber(express_num).setExpressTime(new Date()).update();

            SystemMessage systemMessage = new SystemMessage();
            OrderList orderList = OrderList.dao.findById(id);
            User user = User.dao.findById(orderList.getUserId());
            String message = "您申请的订单已发货，请注意查收！\n订单编号：" + orderList.getOrderNbr();
            systemMessage.setContent(message).setTitle("会员订单：发货通知：").setCreateTime(new Date()).setType(2).setIsDelete(0).setStatus(1).save();



        renderJson(ReturnsUtil.returnSuccess("发货成功"));
    }


    public void getOrderDetail(){
        String id = getPara("id");

        OrderList orderList = OrderList.dao.findById(id);


        Offer offer= Offer.dao.findFirst("select * from offer t where t.status in (0,1) and t.id="+orderList.getOfferId());

        float  tex= offer.getOfferPrice()/100;
        offer.set("offer_price",tex);

        User user = User.dao.findById(orderList.getUserId());
        Address address = Address.dao.findById(orderList.getAddressId());

        float retotal_fee= orderList.getTotalFee()/100;
        orderList.set("total_fee",retotal_fee);
        setAttr("order",orderList);

        setAttr("offer",offer);
        setAttr("user",user);
        setAttr("address",address);


        renderVelocity("/newshop/order/order/orderDetail.html");
    }

    public void update(){
        String id = getPara("id");
        String remark = getPara("remark");

        OrderList orderList= OrderList.dao.findById(id);
        orderList.setRemark(remark).update();

        renderJson(ReturnsUtil.returnSuccess("操作成功"));
    }
}
